<template>
<div>
    <Affix :offset-top="50">
        <Row :gutter="16" class="topBtnDiv" >

             <Col span="4">
            <Button type="primary" icon="android-done" @click="SyncOrgStruct">同步到内存</Button>
            </Col>

        </Row>
    </Affix>
    <Row style="margin-top:20px">
        <Col>
        <div id="SystemModules"></div>
        </Col>

    </Row>

    <Modal v-model="Form.IsShow" :loading="Form.IsLoading" :title="Form.Title" @on-ok="Form.OkEvent" @on-cancel="Form.CancelEvent" scrollable width="800" >
        <Form ref="EditForm" :model="Form.Data" label-position="top">
            <Row :gutter="16">
                <Col :xs="24" :md="8">
                    <FormItem label="机构类型" prop="OS_Type" :rules="{required: true, message:'不能为空', trigger: 'change'}">
                        <DictSelect :readOnly="Form.Data.readOnly" :allowClear="!Form.Data.readOnly"  :multiple="false"  v-model="Form.Data.OS_Type"  label="OrgStructType"  placeholder='请选择'></DictSelect>
                    </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                    <FormItem v-if="Form.Data.OS_Type=='001'" label="所属系统" prop="OS_PlatFormID" :rules="{required: true,type:'number', message:'不能为空', trigger: 'change'}">
                        <Select v-model="Form.Data.OS_PlatFormID" clearable >
                            <Option v-for="item in PlatformItems" :value="item.IP_ID" :key="item.IP_ID">{{ item.IP_Name }}</Option>
                        </Select>
                    </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                    <FormItem v-if="Form.Data.OS_Type=='001'" label="选择系统套餐" prop="OS_PlatformRuleID" :rules="{required: true,type:'number', message:'不能为空', trigger: 'change'}">
                        <Select v-model="Form.Data.OS_PlatformRuleID" clearable>
                            <Option v-for="item in _PlatformItems" :value="item.RuleID" :key="item.RuleID">{{ item.RuleName }}</Option>
                        </Select>
                    </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                <FormItem label="机构名称" prop="OS_Name" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.OS_Name"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                <FormItem label="机构编码" prop="OS_Name" :rules="{required: false, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.OS_Code"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                    <FormItem label="负责人" prop="OS_Admin_UserID">
                        <UserSelect :multiple="false" v-model="Form.Data.OS_Admin_UserID" :partners-id="CurUserInfo.UserPartnersID" btn-text="选择负责人"  placeholder='请选择'></UserSelect>
                    </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                    <FormItem v-if="Form.Data.OS_Type=='001'" label="所属区域" prop="OS_AreaCode">
                        <DictSelect :multiple="false"  v-model="Form.Data.OS_AreaCode"  label="area"  placeholder='请选择'></DictSelect>
                    </FormItem>
                </Col>

                <Col :xs="24" :md="8">
                <FormItem v-if="Form.Data.OS_Type=='001'" label="地址" prop="OS_Addr" :rules="{required: false, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.OS_Addr"></Input>
                </FormItem>
                </Col>

                <Col :xs="24" :md="24">
                <FormItem v-if="Form.Data.OS_Type=='001'" label="备注信息" prop="OS_Desc" :rules="{required: false, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="Form.Data.OS_Desc"></Input>
                </FormItem>
                </Col>








            </Row>
        </Form>
    </Modal>



</div>
</template>

<script>
import then from 'thenjs';
import AppFrame from '../../../libs/app-frame';
import PartnersSelect from '../../../components/partners-select';
import {
    setTimeout
} from 'timers';
import DictSelect from "../../../components/dict-select";
import UserSelect from '../../../components/user-select';
export default {
    components:{
        DictSelect,
        PartnersSelect,
        UserSelect
    },
    data: function() {
        let self = this;
        let MainData = {
            CurSelectNode: null,
            TreeData: []
        };
        let Form = {
            IsShow: false,
            IsLoading: true,
            Data: {
                OS_Type: ''
            },
            OkEvent: function() {
                self.$refs["EditForm"].validate((valid) => {
                    if (valid) {
                        AppFrame.Http.Post("/manage-api/System/org-struct/Edit", Form.Data, function(err, ret) {
                            //console.log(ret);
                            if (ret && ret.Result == 1) {

                                var NodeData = self.GetNodeData(ret.Data);
                                //console.log(NodeData);
                                if (Form.Data.Type == "Edit") {
                                    self.EditNode(NodeData);
                                } else {
                                    self.AddNode(NodeData);
                                }
                                Form.IsShow = false;
                                self.$Message.success('操作成功');
                            } else {
                                self.$Message.error('操作错误,请重试');
                                Form.IsLoading = false;
                                setTimeout(function() {
                                    Form.IsLoading = true;
                                }, 0);
                            }
                        })
                    } else {
                        Form.IsLoading = false;
                        setTimeout(function() {
                            Form.IsLoading = true;
                        }, 0);
                    }
                });
            },
            CancelEvent: function() {},
            SelectModelIDEvent: function(value) {}
        };
        return {
             CurUserInfo: {},
            MainData: MainData,
            PlatformRuleItems:[],
            PlatformItems:[],
            CurSelectNode: null,
            Form: Form,
            FileNameList: [],
            RollBackWin: {
                IsShow: false,
                IsLoading: true,
                FileName: ''
            },
            tree:null,
            QueryModel:{
                partnersId:0
            }
        }
    },
    computed:{
        _PlatformItems:function(){

            let self=this;
            let res=[];
            if(this.Form.Data.OS_PlatFormID>0){
                for(let i=0;i<self.PlatformRuleItems.length;i++){
                    if(self.PlatformRuleItems[i].RulePlatformID==self.Form.Data.OS_PlatFormID){
                        res.push(self.PlatformRuleItems[i]);
                    }
                }
                return res;

            }
            return [];
        }
    },
    created() {
        var self = this;
        this.renderTree();
        this.CurUserInfo = AppFrame.UserInfo.getUserInfo();


    },

    methods: {
        SyncOrgStruct() {
            let self = this;
            AppFrame.Http.Post("/manage-api/system/org-struct/syncOrg", {}, function(err, ret) {
                // console.log(ret);
                if (ret.Result == 1) {
                    self.$Message.success("同步成功！");
                } else {
                    self.$Message.error("同步失败！");
                }
            });
        },
        GetTreeData(cb) {

            let self = this;
            var _TreeData = [];
            _TreeData.push({
                id: '0',
                text: " 组织结构",
                parent: "#",
                icon: "fa fa-folder"
            });

            then(function(defer) {
                let PostData={
                    PartnersID:self.QueryModel.partnersId
                };
                AppFrame.Http.Post("/manage-api/system/org-struct/getItems", PostData, defer);
            }).then(function(defer, ret) {
                // alert(JSON.stringify(ret));
                if (ret && ret.Result == 1) {
                    self.PlatformRuleItems=ret.Data.PlatformRuleItems;
                    self.PlatformItems=ret.Data.PlatformItems;
                    defer(null, ret.Data.orgItems);
                } else {
                    defer({
                        Result: 0
                    });
                }
            }).fin(function(defer, err, ret) {
                if (err) {
                    if (cb) cb(err);
                } else {

                    ret.map(function(item) {
                        var Node = self.GetNodeData(item);
                        _TreeData.push(Node);
                    });
                    // console.log(_TreeData);
                    if (cb) cb(null, _TreeData);
                }
            })

        },

        GetNodeData(Module) {
            var Node = {
                id: Module.OS_ID,
                parent: Module.OS_ParentID,
                text: Module.OS_Name,
                type: Module.OS_IsParent == 1 ? "parent" : "children",
                a_attr: { //自定义a标签的属性
                    OS_ID: Module.OS_ID,
                    OS_Name: Module.OS_Name,
                    OS_Type: Module.OS_Type,
                    OS_Sort: Module.OS_Sort,
                    OS_IsParent: Module.OS_IsParent,
                    OS_IsShow: Module.OS_IsShow,
                    OS_ParentID: Module.OS_ParentID,
                    OS_CreateTime: Module.OS_CreateTime,
                    OS_IsDel: Module.OS_IsDel,
                    OS_Code:Module.OS_Code,
                    OS_Admin_UserID:Module.OS_Admin_UserID,
                    OS_Addr:Module.OS_Addr,
                    OS_Desc:Module.OS_Desc,
                    OS_PlatformRuleID:Module.OS_PlatformRuleID,
                    OS_PlatFormID:Module.OS_PlatFormID,
                    OS_AreaCode:Module.OS_AreaCode
                }

            }
            return Node;
        },

        RenderEditForm(type, node) {

            var self = this;
            var TreeData = self.MainData.TreeData;
            self.Form.Title = "添加下级";
            var Model = {
                Type: type
            };
            if (node) {
                Model.OS_ParentID = node.a_attr.OS_ParentID;
                //Model.ParentID = node.a_attr.OS_ParentID;
                Model.OS_ID = node.a_attr.OS_ID;
                Model.OS_Name = node.a_attr.OS_Name;
                Model.OS_Type = node.a_attr.OS_Type;
                Model.OS_Sort = node.a_attr.OS_Sort;
                Model.OS_IsParent = node.a_attr.OS_IsParent;
                Model.OS_IsShow = node.a_attr.OS_IsShow;
                Model.OS_CreateTime = node.a_attr.OS_CreateTime;
                Model.OS_IsDel = node.a_attr.OS_IsDel;
                Model.OS_Code=node.a_attr.OS_Code,
                    Model.OS_Admin_UserID=node.a_attr.OS_Admin_UserID,
                    Model.OS_Addr=node.a_attr.OS_Addr,
                    Model.OS_Desc=node.a_attr.OS_Desc,
                    Model.OS_PlatformRuleID=node.a_attr.OS_PlatformRuleID,
                    Model.OS_PlatFormID=node.a_attr.OS_PlatFormID,
                    Model.OS_AreaCode=node.a_attr.OS_AreaCode,
                    Model.readOnly=true
                Model.ChildrenNode = [];
                for (var i = 1; i < TreeData.length; i++) {
                    if (TreeData[i].a_attr.OS_ParentID == Model.OS_ID) {
                        Model.ChildrenNode.push(TreeData[i]);
                    }
                }

                self.Form.Title = "修改 - " + Model.OS_Name;
                if(Model.OS_Type==='001'){
                    self.Form.Title+=` 企业管理员用户名：admin:${Model.OS_ID}`;
                }

            } else {
                Model.OS_ParentID = this.MainData.CurSelectNode.id;
                //Model.ParentID = this.MainData.CurSelectNode.id;
                Model.ChildrenNode = [];
                Model.OS_ID = '';
                Model.OS_Name = "";
                Model.OS_Type = "";
                Model.OS_Sort = "";
                Model.OS_IsParent = 0;
                Model.OS_IsShow = 1;
                Model.OS_CreateTime = '';
                Model.OS_IsDel = 0;
            }
            self.Form.IsShow = true;
            self.Form.Data = Model;
        },


        renderTree() {
            let self = this;
            /**初始化JsTree */
            function InitSystemModules() {


                function initJsTree(TreeData) {


                    if(self.tree!=null){
                        self.tree.destroy();

                    }
                    $("#SystemModules").on("select_node.jstree", function(e, data) {
                        self.MainData.CurSelectNode = data.node;
                    });

                    $("#SystemModules").on("move_node.jstree", function(e, data) {
                        //console.log(111);
                        var TargetNode = self.tree.get_node(data.parent);
                        var PostData = {
                            CurNodeID: data.node.id,
                            TargetParentID: data.parent,
                            old_parent: data.old_parent,
                            TargetNodeChildrensIDs: TargetNode.children.join(',')
                        }
                        self.CheckIsParent(PostData.TargetParentID);
                        self.CheckIsParent(data.old_parent);
                        AppFrame.Http.Post("/manage-api/system/org-struct/Move", PostData, function(BackData) {
                            if (BackData.Result == 0) {
                                self.$Message.success(BackData.Msg);
                            }
                        });
                    });

                    $("#SystemModules").jstree({
                        "core": {
                            "multiple": false,
                            "themes": {
                                "variant": "large",
                                "responsive": false,
                            },
                            // so that create works
                            "check_callback": true,
                            'data': TreeData
                        },
                        "types": {
                            "default": {
                                "icon": " fa fa-link"
                            },
                            "parent": {
                                "icon": " fa fa-bookmark"
                            }
                        },
                        "plugins": ["wholerow", "contextmenu", "dnd", "state", "types"],
                        "state": {
                            "key": "SystemModules"
                        },
                        "contextmenu": {
                            "items": contextmenu
                        }
                    });
                    self.tree = $.jstree.reference('#SystemModules');

                }

                //console.log(222);
                self.GetTreeData(function(err, TreeData) {
                    self.MainData.TreeData.splice(0,self.MainData.TreeData.length);
                    self.MainData.TreeData = TreeData;
                    initJsTree(TreeData);
                });

            }

            function contextmenu(node) {

                var items = {
                    edititem: {
                        label: "修改",
                        icon: "glyphicon glyphicon-edit ",
                        action: function() {
                            self.RenderEditForm("Edit", node);
                        }
                    },
                    deleteitem: {
                        label: "删除",
                        icon: "glyphicon glyphicon-remove   ",
                        action: function() {
                            self.DeleteNode(node);
                        }
                    },
                    additem: {
                        label: "添加下级",
                        icon: "glyphicon glyphicon-saved ",
                        action: function() {
                            self.RenderEditForm("Add");
                        }
                    }
                };

                if (node.parent == ("#")) {

                    delete items.deleteitem;
                    delete items.edititem;
                }

                if(node.id==self.CurUserInfo.UserPartnersID){
                    delete items.deleteitem;
                    delete items.edititem;
                }

                return items;
            };

            InitSystemModules();
        },


        /**
         * 添加 节点
         * @param NodeData
         * @constructor
         */
        AddNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            var tree = $.jstree.reference('#SystemModules');
            tree.create_node(CurSelectNode, NodeData);
            this.CheckIsParent(CurSelectNode.id);
            tree.open_node(CurSelectNode);
            tree.deselect_all();
            tree.select_node(NodeData);
            this.MainData.TreeData.push(NodeData);
        },


        /**
         * 编辑 节点
         * @param NodeData
         * @constructor
         */
        EditNode(NodeData) {
            var CurSelectNode = this.MainData.CurSelectNode;
            CurSelectNode.a_attr = NodeData.a_attr;
            CurSelectNode.text = NodeData.text;
            $.jstree.reference('#SystemModules').set_text(CurSelectNode, NodeData.text);
        },

        /**
         * 删除节点
         * @param NodeData
         * @constructor
         */
        DeleteNode(node) {
            var self = this;
            this.$Modal.confirm({
                title: "提示",
                content: "确实要删除 [" + node.text + "] 吗?",
                loading: true,
                onCancel: () => {
                    self.$Modal.remove();
                },
                onOk: () => {
                    var AllIchildrenIDs = node.children_d;
                    var AllIDs = AllIchildrenIDs.join(',') + "," + node.id;
                    var PostData = {
                        AllIDs: AllIDs,
                        CurNodeID: node.id,
                        CurNodeParentID: node.a_attr.OS_ParentID
                    }

                    var tree = $.jstree.reference('#SystemModules');
                    tree.delete_node(node);
                    self.CheckIsParent(node.a_attr.OS_ParentID);
                    var AllIDsArray = AllIDs.split(",");
                    for (var id in AllIDsArray) {
                        if (AllIDsArray[id] != "") {
                            for (var i = self.MainData.TreeData.length - 1; i >= 0; i--) {
                                if (self.MainData.TreeData[i].id == Number(AllIDsArray[id])) {
                                    self.MainData.TreeData.splice(i, 1);
                                    break;
                                }
                            }
                        }

                    }

                    AppFrame.Http.Post("/manage-api/System/org-struct/Del", PostData, function(err, BackData) {
                        self.$Modal.remove();
                        //console.log(BackData);
                        if (BackData && BackData.Result == 1) {
                            self.$Message.success('操作成功');
                        } else {
                            self.$Message.error('操作失败');
                        }

                    })


                },
            });
        },


        Publish() {
            var self = this;
            this.$Modal.confirm({
                title: "提示",
                content: "确实要发布吗?",
                loading: true,
                onCancel: () => {
                    self.$Modal.remove();
                },
                onOk: () => {
                    AppFrame.Http.Post("/manage-api/System/system-module/Publish", {}, function(err, ret) {
                        //console.log(ret);
                        if (ret && ret.Result == 1) {
                            self.$Message.success('操作成功');
                        } else {
                            self.$Message.error('操作失败');
                        }
                        self.$Modal.remove();
                    })
                }
            });
        },

        RollBack() {
            var self = this;
            this.RollBackWin.IsShow = true;
            AppFrame.Http.Post("/manage-api/system/system-module/GetJsonFile", {}, function(err, ret) {
                if (ret && ret.Result == 1) {
                    self.FileNameList = ret.Data;
                }
            })
        },
        DoRollBack() {
            var self = this;
            var selectFileName = self.RollBackWin.FileName;
            if (selectFileName == '') {
                self.$Message.error('请选择需要恢复的文件');
                self.RollBackWin.IsLoading = false;
                setTimeout(function() {
                    self.RollBackWin.IsLoading = true;
                }, 0);
            };
            AppFrame.Http.Post("/manage-api/system/system-module/RollBack", {
                FileName: selectFileName
            }, function(err, ret) {
                if (ret && ret.Result == 1) {
                    self.RollBackWin.IsShow = false;
                    self.$Message.success('恢复成功');
                }
            })

        },

        /**
         * 检测是否是父级
         * @param NodeID
         * @constructor
         */
        CheckIsParent(NodeID) {
            if (NodeID == 0) return;
            var tree = $.jstree.reference('#SystemModules');
            var ParentNode = tree.get_node(NodeID);
            if (ParentNode) {
                if (ParentNode.children.length > 0) {
                    ParentNode.type = "parent";
                    ParentNode.a_attr.IsParent = 1;
                    tree.set_icon(ParentNode, "fa fa-bookmark ");
                } else {
                    ParentNode.type = "children";
                    ParentNode.a_attr.IsParent = 0;
                    tree.set_icon(ParentNode, "fa fa-link   ");
                }
            }
        }
    }
}
</script>

<style scoped>
.topBtnDiv {
    line-height: 40px;
    background-color: #fff;
}
</style>
